<?php
/**
 * Database abstraction class.
 * Works with SQLite only at the moment.
 */
class AtbudgetDB extends SQLite3 {
	function __construct($fname)
	{
		$this->open($fname);
		$this->busyTimeout(2000);
	}
}

	$db = new AtbudgetDB('../atbudget.sqlite');
	try {
		switch ($_SERVER['REQUEST_METHOD']) {
			case 'GET': //list currencies
				header('Content-type: application/json');
				$res = $db->query('SELECT * FROM currency');
				$currencies = array();
				$i = 0;
				if ($res) {
					while ($row = $res->fetchArray(SQLITE3_ASSOC)) {
						$currencies[$i] = $row;
						$i++;
					}
				}
				echo json_encode(array('success' => 'true', 'currencies' => $currencies));
				break;
			case 'POST': //new currency
				header('Content-type: application/json');
				$cur = json_decode($HTTP_RAW_POST_DATA);
				if (($cur->name == '') || ($cur->code == '')) {
					echo json_encode(array('success' => 'false', 'msg' => 'Failed to create record. Invalid data.','currencies' => array()));
				} else {
					if ($db->exec('INSERT INTO currency (name, code, prefix, suffix, thousands, decimal, precision) VALUES ("'.$cur->name.'","'.$cur->code.'","'.$cur->prefix.'","'.$cur->suffix.'","'.$cur->thousands.'","'.$cur->decimal.'",'.$cur->precision.')')) {
						$cur->id = $db->lastInsertRowID();
						echo json_encode(array('success' => 'true','currencies' => array($cur)));
					} else {
						echo json_encode(array('success' => 'false', 'msg' => 'Failed to create record. Database failure.','currencies' => array()));
					}
				}
				break;
			case 'PUT': //save currency
				header('Content-type: application/json');
				echo json_encode(array('success' => 'false', 'msg' => 'Not implemented yet.', 'currencies' => array()));
				break;
			case 'DELETE': //delete currency
				header('Content-type: application/json');
				echo json_encode(array('success' => 'false', 'msg' => 'Not implemented yet.', 'currencies' => array()));
				break;
			default:
				header('Content-type: application/json');
				echo json_encode(array('success' => 'false', 'msg' => 'Server cannot handle your request.','currencies' => array()));
		}//switch
	} catch (Exception $e) {
	}
	$db->close();
